<template>
    <div class="release_box">
        <Toolbar :editor="editorRef" :mode="mode" />
        <el-input v-model="title" placeholder="请输入标题~~" class="title-inp" />
        <el-input v-model="abstract" placeholder="请输入摘要~~" class="abstract-inp" />
        <Editor style="height: 4rem; overflow-y: hidden;" v-model="valueHtml" @onCreated="handleCreated"
            :defaultConfig="editorConfig" :mode="mode" />
        <div class="select-input">
            <div class="class-add">
                <el-input class="class-inp" v-model="classText" maxlength="20" placeholder="请输入要添加的类名" show-word-limit
                    type="text" />
                <el-button color="#0099ff" class="add-btn" @click="btnAdd">添加</el-button>
            </div>
            <el-select v-model="arr" multiple placeholder="请选择分类" @change="changeClass" class="class-sel">
                <el-option v-for="item in options" :key="item.labelClass" :label="item.labelClass"
                    :value="item.labelClass" />
            </el-select>
            <el-button color="#0099ff" class="class-btn" @click="btnRelease">发布</el-button>
        </div>
        <el-dialog v-model="centerDialogVisible" title="消息提示" width="30%" center>
            <span>您确定要添加<span style="color: #0099ff; font-size: .2rem;">{{ classText }}</span>这个标签吗?</span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="centerDialogVisible = false" class="dialog">取消</el-button>
                    <el-button type="primary" @click="btnDetermine" class="dialog">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, nextTick, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from "../axios/index.js"
import Prism from "prismjs";
import "prismjs/themes/prism.css"
import "prismjs/themes/prism-okaidia.css"
import { ElMessage } from 'element-plus'
components: { Editor, Toolbar }
// 标题输入框的内容
let title = ref("")
// 标签选中项的数组
const arr = ref([])
// 下拉框内容数组
const options = ref([])
// 添加标签的内容
let classText = ref("")
// 对话框显示与隐藏
let centerDialogVisible = ref(false)
// 文章摘要
let abstract = ref("")
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

//输入框的配置项
const editorConfig = {
    placeholder: '请输入内容...',                      // JS 语法
    MENU_CONF: {},
}

editorConfig.MENU_CONF['uploadImage'] = {
    // 自定义上传
    async customUpload(file, insertFn) {                   // JS 语法
        const formData = new FormData()
        formData.append("img", file, file.name)
        let { data: { data } } = await axios.post("/upload", formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            },
        });
        insertFn(`http://localhost:8848${data}`)
    },
    customInsert(res, insertFn) {                  // JS 语法
    },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}
let mode = ref('default')

editorConfig.MENU_CONF['codeSelectLang'] = {
    // 代码语言
    codeLangs: [{
        text: 'CSS',
        value: 'css'
    },
    {
        text: 'HTML',
        value: 'html'
    },
    {
        text: 'XML',
        value: 'xml'
    },
    {
        text: 'Javascript',
        value: 'javascript'
    },
    {
        text: 'Typescript',
        value: 'typescript'
    },
    {
        text: 'JSX',
        value: 'jsx'
    },
    {
        text: 'Go',
        value: 'go'
    },
    {
        text: 'PHP',
        value: 'php'
    },
    {
        text: 'C',
        value: 'c'
    },
    {
        text: 'Python',
        value: 'python'
    },
    {
        text: 'Java',
        value: 'java'
    },
    {
        text: 'C++',
        value: 'cpp'
    },
    {
        text: 'C#',
        value: 'csharp'
    },
    {
        text: 'Visual Basic',
        value: 'visual-basic'
    },
    {
        text: 'SQL',
        value: 'sql'
    },
    {
        text: 'Ruby',
        value: 'ruby'
    },
    {
        text: 'Swift',
        value: 'swift'
    },
    {
        text: 'Bash',
        value: 'bash'
    },
    {
        text: 'Lua',
        value: 'lua'
    },
    {
        text: 'Groovy',
        value: 'groovy'
    },
    {
        text: 'Markdown',
        value: 'markdown'
    },
    ]
}

onMounted(async () => {
    let { data } = await axios.get("/class/init")
    options.value = data
});

// nextTick(()=>{
//     Prism.highlightAll();
// })

// 监听下拉框多选内容变化
const changeClass = (options) => {
    // 最多允许四个标签
    if (options.length > 4) {
        ElMessage({
            message: '标签名最多只能为四个',
            type: 'warning',
            duration: 2000
        })
        options.pop()
    }
}

// 添加标签按钮点击事件
const btnAdd = () => {
    console.log(classText.value)
    if (classText.value) {
        centerDialogVisible.value = true
        return
    } else {
        ElMessage({
            message: '标签名不能为空',
            type: 'warning',
            duration: 2000
        })
    }
}

// 确定添加标签按钮点击事件
const btnDetermine = async () => {
    centerDialogVisible.value = false
    let { data } = await axios.get(`/class/addClass?classText=${classText.value}`)
    if (data.code === 2) {
        ElMessage({
            message: `${data.classText}添加成功`,
            type: 'success',
            duration: 2000
        })
        classText.value = ""
        let datas = await axios.get("/class/init")
        options.value = datas.data
        return
    } else if (data.code === 1) {
        ElMessage({
            message: `${data.classText}已存在`,
            type: 'warning',
            duration: 2000
        })
        classText.value = ""
    }
}

// 发布按钮点击事件处理函数
const btnRelease = async () => {
    if (!title.value) {
        ElMessage({
            message: `请填写标题`,
            type: 'warning',
            duration: 2000
        })
        return
    } else if (!abstract.value) {
        ElMessage({
            message: `请填写摘要`,
            type: 'warning',
            duration: 2000
        })
        return
    } else if (valueHtml.value === "<p><br></p>") {
        ElMessage({
            message: `请填写博客内容`,
            type: 'warning',
            duration: 2000
        })
        return
    } else if (arr.value.length === 0) {
        ElMessage({
            message: `最少选择一个标签作为您的博客分类`,
            type: 'warning',
            duration: 2000
        })
        return
    } else {
        let addObj = {
            label: title.value,
            abstract: abstract.value,
            blog: valueHtml.value,
            time: getNowTime(),
            visitsNum: "0",
            arr: JSON.stringify(arr.value),
        }
        let { data } = await axios.put("/blog/addBlog", addObj)
        if (data === 1) {
            ElMessage({
                message: `博客发布成功`,
                type: 'success',
                duration: 2000
            })
            // 清空输入框内容
            title.value = ""
            abstract.value = ""
            valueHtml.value = ""
            arr.value = []
            return
        } else {
            ElMessage({
                message: `博客发布失败，请致电15549583521`,
                type: 'warning',
                duration: 2000
            })
        }
    }
}

// 获取当前时间字符串
function getNowTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var time = year + '-' + addZero(month) + '-' + addZero(day) + ' ' + addZero(hour) + ':' + addZero(minute) +
        ':' + addZero(second);
    return time;
}

function addZero(s) {
    return s < 10 ? ('0' + s) : s;
}
</script>

<style scoped lang="less">
.release_box {
    width: 15.2rem;

    .dialog {
        padding: .05rem .1rem;
    }

    .title-inp {
        ::v-deep .el-input__wrapper {
            color: #eee;
            height: .4rem;
            margin: .2rem 0;
            border-radius: 0.12rem;
            border: .01rem solid @nav-bgc;
            background-color: rgba(255, 255, 255, 0.8);
            box-sizing: border-box;
        }
    }

    .abstract-inp {
        ::v-deep .el-input__wrapper {
            color: #eee;
            height: .4rem;
            margin: 0 0 .2rem 0;
            border-radius: 0.12rem;
            border: .01rem solid @nav-bgc;
            background-color: rgba(255, 255, 255, 0.8);
            box-sizing: border-box;
        }
    }

    ::v-deep .w-e-bar {
        border-radius: 0.12rem;
        background-color: rgba(255, 255, 255, 0.8);
        border: .01rem solid @nav-bgc;
        box-sizing: border-box;
    }

    ::v-deep .w-e-text-container {
        border-radius: 0.12rem;
        background-color: rgba(255, 255, 255, 0.8);
        border: .01rem solid @nav-bgc;
        box-sizing: border-box;
    }

    .select-input {
        width: 100%;
        border-radius: 0.12rem;
        background-color: rgba(255, 255, 255, 0.8);
        border: .01rem solid @nav-bgc;
        box-sizing: border-box;
        margin-top: .2rem;
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: .2rem 0;

        .class-add {
            width: 40%;

            .class-inp {
                width: 85%;
                height: .36rem;
            }

            .add-btn {
                width: 15%;
                height: .34rem;
            }
        }

        .class-sel {
            width: 30%;
            height: .36rem;
        }

        .class-btn {
            width: 10%;
            height: .34rem;
        }
    }
}
</style>
